using MediatR;
using B.S.BasicData.Infrature;
using B.S.BasicData.Domain;
using B.S.BasicData.EroorCode;
using Microsoft.EntityFrameworkCore;

namespace B.S.BasicData.Api
{
    public class SlaughterEnterpriseInfoQueryByAddressHandler : IRequestHandler<SlaughterEnterpriseInfoQueryByAddressRequest, ApiResult<List<SlaughterEnterpriseInfo>>>
    {
        private readonly AppDbContext _context;

        public SlaughterEnterpriseInfoQueryByAddressHandler(AppDbContext context)
        {
            _context = context;
        }

        public async Task<ApiResult<List<SlaughterEnterpriseInfo>>> Handle(SlaughterEnterpriseInfoQueryByAddressRequest request, CancellationToken cancellationToken)
        {
            try
            {
                var query = _context.SlaughterEnterpriseInfos.AsQueryable();

                // 根据省份筛选
                if (!string.IsNullOrWhiteSpace(request.Province))
                {
                    query = query.Where(x => x.CompanyAddress.Contains(request.Province));
                }

                // 根据城市筛选
                if (!string.IsNullOrWhiteSpace(request.City))
                {
                    query = query.Where(x => x.CompanyAddress.Contains(request.City));
                }

                // 根据县/区筛选
                if (!string.IsNullOrWhiteSpace(request.County))
                {
                    query = query.Where(x => x.CompanyAddress.Contains(request.County));
                }

                var result = await query.ToListAsync(cancellationToken);

                return ApiResult<List<SlaughterEnterpriseInfo>>.Success(result, "查询成功");
            }
            catch (Exception ex)
            {
                return ApiResult<List<SlaughterEnterpriseInfo>>.Fail($"查询失败: {ex.Message}", ApiResultCode.Error);
            }
        }
    }
} 